package com.yunxi.service.dubboService.impl.otd;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunxi.bizToHub.pojo.EaiLogs;
import com.yunxi.bizToHub.service.EaiLogBizToHubService;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.DictConstant;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.hubToBiz.service.OtdSendPlanDubboService;
import com.yunxi.model.otd.OtdInterfaceConfig;
import com.yunxi.model.otd.OtdOrderCir;
import com.yunxi.model.otd.OtdOrderSo;
import com.yunxi.rocketMq.producer.OtdMonthPlanProducer;
import com.yunxi.rocketMq.producer.OtdWeekPlanProducer;
import com.yunxi.service.localService.otd.OtdInterfaceConfigService;
import com.yunxi.service.localService.otd.OtdOrderCirService;
import com.yunxi.service.localService.otd.OtdOrderSoService;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;

public class OtdSendPlanDubboServiceImpl implements OtdSendPlanDubboService {

    private static final Logger logger = LoggerFactory.getLogger(OtdSendPlanDubboServiceImpl.class);

    @Autowired
    @Qualifier("otdOrderSoServiceImpl")
    OtdOrderSoService soService;

    @Autowired
    @Qualifier("otdOrderCirServiceImpl")
    OtdOrderCirService cirService;

    @Autowired
    @Qualifier("otdInterfaceConfigServiceImpl")
    OtdInterfaceConfigService configService;

    @Autowired
    private EaiLogBizToHubService eaiLogBizToHubServiceImpl;

    @Autowired
    private OtdWeekPlanProducer otdWeekPlanProducer;

    @Value("${mq.switch}")
    private String mq_switch;

    @Autowired
    private OtdMonthPlanProducer otdMonthPlanProducer;


    /**
     * SO排产订单接口下发
     *
     * @return JSON
     */
    @Override
    public ApiResult sendPlan() {
        //// 1.查询未执行接口下发计划
        LambdaQueryWrapper<OtdInterfaceConfig> wrapper = new LambdaQueryWrapper<>();
        // isOpen:1开启、state:状态不为已发送、executeTime执行时间小于当前时间
        wrapper.eq(OtdInterfaceConfig::getIsOpen, 1)
            .ne(OtdInterfaceConfig::getState, "S")
            .le(OtdInterfaceConfig::getExecuteTime, new Date());
        List<OtdInterfaceConfig> configList = configService.list(wrapper);
        if (CollectionUtils.isEmpty(configList)) {
            logger.info("没有需要执行的任务");
            return ResponseUtil.ok("没有需要执行的任务");
        }
        logger.info("执行任务数量：" + configList.size());
        //// 2.遍历执行
        for (OtdInterfaceConfig config : configList) {
            try {
                Thread.sleep(1000);
                config.setState("S");
                config.setUpdateTime(new Date());
                config.setUpdateBy("PMS后台任务");

                if ("CIR".equals(config.getType())) {
                    ///////  月计划
                    logger.info("月计划下发开始，订单类型" + config.getType());
                    // 查询需要发送的CIR数据
                    Map<String, Object> map = new HashMap<>();
                    map.put("startDate", config.getStartDate());
                    map.put("endDate", config.getEndDate());
                    List<OtdOrderCir> orderList = cirService.listBy(map);
                    if (CollectionUtils.isEmpty(orderList)) {
                        throw new RuntimeException("未找到需要发送数据");
                    }
                    // 转换JSON
                    String json = cirService.generateSapJson(orderList);
                    logger.info("月计划接口下发，JSON:\n" + json);
                    if (mq_switch.equals("true")) {
                        logger.info("月计划接口发送MQ");
                        otdMonthPlanProducer.sendMessage(json);
                    } else {
                        logger.info("月计划接口发送EaiLogs");
                        EaiLogs eaiLogs = new EaiLogs();
                        eaiLogs.setPmsEaiContent(json);
                        eaiLogBizToHubServiceImpl.saveMonthPlanEaiLog(eaiLogs);
                    }
                } else {
                    ///////  周计划（普通需求/项目用车）
                    logger.info("周计划下发开始，订单类型" + config.getType());
                    // 查询待发送接口数据
                    //接口发送类型：国内+海外
                    String orderType = DictConstant.OTD_ORDER_TYPE_INVE + "," + DictConstant.OTD_ORDER_TYPE_EXVE;
                    if ("PSO".equals(config.getType())) {
                        orderType = DictConstant.OTD_ORDER_TYPE_PRVE;
                    }
                    List<OtdOrderSo> orderList = soService
                        .findSendOrderSo(orderType, config.getStartDate(), config.getEndDate());
                    if (CollectionUtils.isEmpty(orderList)) {
                        throw new RuntimeException("未找到需要发送数据");
                    }
                    // 转换JSON
                    String json = soService.generateSapJson(orderList);
                    logger.info("周计划接口下发，订单类型" + config.getType() + "，JSON:\n" + json);
                    if (mq_switch.equals("true")) {
                        logger.info("周计划接口发送MQ");
                        otdWeekPlanProducer.sendMessage(json);
                    } else {
                        EaiLogs eaiLogs = new EaiLogs();
                        eaiLogs.setPmsEaiContent(json);
                        eaiLogBizToHubServiceImpl.saveWeekPlanEaiLog(eaiLogs);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("执行计划"+ config.getId() +"生产计划接口ERROR:" + e.getMessage());
                if(!StringUtils.isEmpty(e.getMessage())){
                    config.setMessage(
                        e.getMessage().substring(0, Math.min(e.getMessage().length(), 200)));
                }
                config.setState("E");
            } finally {
                configService.updateById(config);
            }
        }
        return ResponseUtil.ok();
    }
}
